//
//  FBMessageHUD.m
//  FBPersonalCenterProject
//
//  Created by Chenjing on 2017/7/3.
//  Copyright © 2017年 YunJing. All rights reserved.
//

#import "FBMessageHUD.h"

#define DEF_KEYWINDOW [UIApplication sharedApplication].keyWindow

#define DEF_SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width

#define DEF_SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

/**
 *  @brief 提示消息框的最小高度
 */
#define DEF_MIN_HEIGHT 40

/**
 *  @brief 文字距消息框边缘的距离
 */
#define DEF_TEXT_SPACE 17

/**
 *  @brief 文字消息框到Window的最小距离
 */
#define DEF_MESSAGE_SPACE 20

/**
 *  @brief 文字消息框距Window底部的最小距离
 */
#define DEF_MESSAGE_HEIGHT_BOTTOM 66

/**
 *  @brief 图文消息框的尺寸
 */
#define DEF_MESSAGE_IMAGETEXT_SIZE CGSizeMake(120, 120)

/**
 *  @brief 图文消息框边界
 */
#define DEF_MESSAGE_IMAGETEXT_SPACE 26

/**
 *  @brief 动画显示的动画时间
 */
#define DEF_MESSAGE_SHOW_ANIMATEDTIME 0.5

/**
 *  @brief 动画消失的动画时间
 */
#define DEF_MESSAGE_DISAPPEAR_ANIMATEDTIME 0.3


/**
 *  @brief 默认字体大小
 */
#define DEF_MESSAGE_TEXTFONT [UIFont systemFontOfSize:14.0f]
#define DEF_MESSAGE_TEXTCOLOR [UIColor whiteColor]



@interface FBMessageHUD ()<CAAnimationDelegate>

@property (nonatomic, strong) UILabel *textLb;

@property (nonatomic, strong) UIImageView *imageView;

@end


@implementation FBMessageHUD

#pragma mark - Class Meyhod

/**
 *  @breif  纯文字类型的信息提示
 */
+ (void)showMessageWithText:(NSString *)text {
    [[FBMessageHUD shareInstance] showMessageWithImage:nil text:text attributes:nil backgroundColor:nil];
}

/**
 *  @breif  纯图片类型的信息提示
 */
+ (void)showMessageWithImage:(UIImage *)image {
    [[FBMessageHUD shareInstance] showMessageWithImage:image text:nil attributes:nil backgroundColor:nil];
}


/**
 *  @breif  自定义类型的信息提示
 */
+ (void)showMessageWithImage:(UIImage *)image text:(NSString *)text {
    [[FBMessageHUD shareInstance] showMessageWithImage:image text:text attributes:nil backgroundColor:nil];
}

/**
 *  @breif  纯文字类型的信息提示
 */
+ (void)showMessageWithText:(NSString *)text attributes:(NSDictionary *)attributes {
    [[FBMessageHUD shareInstance] showMessageWithImage:nil text:text attributes:attributes backgroundColor:nil];
}


/**
 *  @breif  自定义信息提示
 */
+ (void)showMessageWithImage:(UIImage *)image text:(NSString *)text attributes:(NSDictionary *)attributes {
    [[FBMessageHUD shareInstance] showMessageWithImage:image text:text attributes:attributes backgroundColor:nil];
}


/**
 *  @breif  图文类型的信息提示
 */
+ (void)showMessageWithImage:(UIImage *)image text:(NSString *)text attributes:(NSDictionary *)attributes backgroundColor:(UIColor *)backgroundColor {
    [[FBMessageHUD shareInstance] showMessageWithImage:image text:text attributes:attributes backgroundColor:backgroundColor];
}


#pragma mark - deprecated
/**
 *  @breif  成功类型的信息提示
 */
+ (void)showSuccessMessageWithText:(NSString *)text {
    [[FBMessageHUD shareInstance] showMessageWithImage:nil text:text attributes:nil backgroundColor:nil];
}

/**
 *  @breif  根据信息类别提示
 */
+ (void)showFailedMessageWithText:(NSString *)text {
    [[FBMessageHUD shareInstance] showMessageWithImage:nil text:text attributes:nil backgroundColor:nil];
}

/**
 *  @breif  成功类型的信息提示
 */
+ (void)showSuccessMessageWithText:(NSString *)text attributes:(NSDictionary *)attributes {
    [[FBMessageHUD shareInstance] showMessageWithImage:nil text:text attributes:attributes backgroundColor:nil];
}

/**
 *  @breif  根据信息类别提示
 */
+ (void)showFailedMessageWithText:(NSString *)text attributes:(NSDictionary *)attributes {
    [[FBMessageHUD shareInstance] showMessageWithImage:nil text:text attributes:attributes backgroundColor:nil];
}


#pragma mark - Show && Hide
+ (instancetype)shareInstance {
    
    FBMessageHUD *hud = [[FBMessageHUD alloc]init];
    hud.backgroundColor = [UIColor colorWithWhite:0 alpha:0.8];
    hud.layer.cornerRadius = 4.0f;
    hud.layer.masksToBounds = YES;
    hud.showTime = 1.0f;
    hud.hiddenAutomatically = YES;
    hud.alpha = 0;
    return hud;
}

- (void)showMessageWithImage:(UIImage *)image text:(NSString *)text attributes:(NSDictionary *)attributes backgroundColor:(UIColor *)backgroundColor {
    self.image = image;
    self.text = text;
    self.textAttributes = attributes;
    if (backgroundColor) self.backgroundColor = backgroundColor;
    [self show];
}

- (void)show {
    
    [self configSubViewsAttribiutes];
    [self configSubViewsLayout];
    
    [[self windowTopViewController:[self lastWindow]].view addSubview:self];
    
    [UIView animateWithDuration:DEF_MESSAGE_SHOW_ANIMATEDTIME animations:^{
        self.alpha = 1;
    } completion:^(BOOL finished) {
        if (self.hiddenAutomatically) {
            [self automaticalHidden];
        } else {
            [self addTapGestureRecognizer];
        }
    }];
}

- (__kindof UIViewController *)windowTopViewController:(UIWindow *)window {
    UIViewController *vc = window.rootViewController;
    NSInteger idx = 1;
    while (idx) {
        //根据不同的页面切换方式，逐步取得最上层的viewController
        if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController*)vc).selectedViewController;
        }
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController*)vc).visibleViewController;
        }
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        } else {
            idx += 1;
            if (idx == 10) {
                break;
            } else {
                continue;
            }
        }
    }
    return vc;
}


- (void)automaticalHidden{
    __weak typeof(self) weakself = self;
    dispatch_time_t showTime = dispatch_time(DISPATCH_TIME_NOW, self.showTime * NSEC_PER_SEC);
    dispatch_after(showTime, dispatch_get_main_queue(), ^(void){
        [weakself hiddenHUD];
    });
}

- (void)hiddenHUD {
    [UIView animateWithDuration:DEF_MESSAGE_DISAPPEAR_ANIMATEDTIME animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)showWithAnimationGroup {
    CGPoint center = self.center;
    
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    
    NSValue *value1 = [NSValue valueWithCGPoint:CGPointMake(center.x, center.y + 20)];
    NSValue *value2 = [NSValue valueWithCGPoint:CGPointMake(center.x, center.y - 10)];
    NSValue *value3 = [NSValue valueWithCGPoint:CGPointMake(center.x, center.y)];
    animation.values = @[value1,value2,value3];
    animation.duration = 0.5;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    
    CABasicAnimation * alphaBaseAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    alphaBaseAnimation.fillMode = kCAFillModeForwards;//不恢复原态
    alphaBaseAnimation.duration = 0.5;
    alphaBaseAnimation.removedOnCompletion = NO;
    [alphaBaseAnimation setToValue:[NSNumber numberWithFloat:1]];
    alphaBaseAnimation.fillMode = kCAFillModeForwards;
    
    CAAnimationGroup *animGroup = [CAAnimationGroup animation];
    animGroup.animations = @[alphaBaseAnimation,animation];
    animGroup.removedOnCompletion = NO;
    animGroup.duration = 0.5;
    animGroup.delegate = self;
    animGroup.fillMode = kCAFillModeForwards;
    [self.layer addAnimation:animGroup forKey:@"group"];
}

#pragma mark -
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    if (self.hiddenAutomatically) {
        [self automaticalHidden];
    } else {
        [self addTapGestureRecognizer];
    }
}

#pragma mark - Add TapGesture
- (void)addTapGestureRecognizer {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(messageHudClick:)];
    [self addGestureRecognizer:tap];
    
}

- (void)messageHudClick:(UITapGestureRecognizer *)gesture {
    if (self.TouchBlock) {
        self.TouchBlock(self);
    }
    [self hiddenHUD];
}

#pragma mark - setter Method
- (void)setText:(NSString *)text {
    _text = text;
}

- (void)setTextFont:(UIFont *)textFont {
    _textFont = textFont;
    
}

- (void)setTextColor:(UIColor *)textColor {
    _textColor = textColor;
}

- (void)setTextAttributes:(NSDictionary *)textAttributes {
    _textAttributes = textAttributes;
}


#pragma mark - 设置控件属性
- (void)configSubViewsAttribiutes {
    
    if (!self.textColor) {
        self.textColor = DEF_MESSAGE_TEXTCOLOR;
    }
    
    if (!self.textFont) {
        self.textFont = DEF_MESSAGE_TEXTFONT;
    }
    
    if (!self.textAttributes) {
        self.textAttributes = [NSMutableDictionary dictionaryWithObjects:@[self.textColor,self.textFont,@(0.1)] forKeys:@[NSForegroundColorAttributeName,NSFontAttributeName,NSKernAttributeName]];
    }
    
    if (self.text.length > 0) {
        NSAttributedString *attributeText = [[NSAttributedString alloc]initWithString:self.text attributes:self.textAttributes];
        self.textLb.attributedText = attributeText;
    }
    
    if (self.image) {
        self.imageView.image = self.image;
    }
}


- (void)configSubViewsLayout {
    
    if (self.image && self.text.length > 0 ) {
        [self configSubViewsLayoutTextAndImageContent];
    } else if (self.image) {
        [self configSubViewsLayoutImageContent];
    } else {
        [self configSubViewsLayoutTextContent];
    }
}

//文字信息提示框
- (void)configSubViewsLayoutTextContent {
    CGFloat textWidth = 0;
    CGFloat textHeight = 0;
    CGFloat textAvalibaleWidth = DEF_SCREEN_WIDTH - DEF_MESSAGE_SPACE*2 - DEF_TEXT_SPACE*2;
    CGFloat totalHeight = DEF_MIN_HEIGHT;
    
#ifdef NSFoundationVersionNumber10_10_Max
    if (@available(iOS 11.0, *)) {
        UIEdgeInsets safeInsets = [UIApplication sharedApplication].keyWindow.safeAreaInsets;
        textAvalibaleWidth = DEF_SCREEN_WIDTH - safeInsets.left - safeInsets.right - DEF_MESSAGE_SPACE*2 - DEF_TEXT_SPACE*2;
    }
#endif
    
    //判断是否有文字
    if (self.text.length > 0) {
        CGSize textSize = [self.textLb.attributedText boundingRectWithSize:CGSizeMake(textAvalibaleWidth, DEF_SCREEN_HEIGHT) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
        textWidth = textSize.width;
        textHeight = textSize.height;
        totalHeight = textHeight + 20 > DEF_MIN_HEIGHT ? textHeight + 20 : DEF_MIN_HEIGHT;
        
        self.textLb.frame = CGRectMake(DEF_TEXT_SPACE, 0, textWidth, totalHeight);
        CGRect hudRect = CGRectZero;
        hudRect.origin.x = (DEF_SCREEN_WIDTH - textWidth - DEF_TEXT_SPACE * 2)/2.0;
        hudRect.origin.y = DEF_SCREEN_HEIGHT - DEF_MESSAGE_HEIGHT_BOTTOM - totalHeight;
        
#ifdef NSFoundationVersionNumber10_10_Max
        if (@available(iOS 11.0, *)) {
            hudRect.origin.y = DEF_SCREEN_HEIGHT - DEF_MESSAGE_HEIGHT_BOTTOM - totalHeight - [UIApplication sharedApplication].keyWindow.safeAreaInsets.bottom;
        }
#endif
        hudRect.size.width = textWidth + DEF_TEXT_SPACE * 2;
        hudRect.size.height = totalHeight;
        self.frame = hudRect;
    }
}

//图片信息提示框
- (void)configSubViewsLayoutImageContent {
    self.imageView.frame = CGRectMake(DEF_MESSAGE_IMAGETEXT_SPACE, DEF_MESSAGE_IMAGETEXT_SPACE, DEF_MESSAGE_IMAGETEXT_SIZE.width - DEF_MESSAGE_IMAGETEXT_SPACE * 2, DEF_MESSAGE_IMAGETEXT_SIZE.height - DEF_MESSAGE_IMAGETEXT_SPACE * 2);
    CGFloat center_X = DEF_SCREEN_WIDTH/2.0;
    CGFloat center_Y = DEF_SCREEN_HEIGHT/2.0;
    
#ifdef NSFoundationVersionNumber10_10_Max
    if (@available(iOS 11.0, *)) {
        UIEdgeInsets safeInsets = [UIApplication sharedApplication].keyWindow.safeAreaInsets;
        center_Y = (DEF_SCREEN_HEIGHT - safeInsets.bottom - safeInsets.top)/2.0;
    }
#endif
    self.bounds = CGRectMake(0, 0, DEF_MESSAGE_IMAGETEXT_SIZE.width, DEF_MESSAGE_IMAGETEXT_SIZE.height);
    self.center = CGPointMake(center_X, center_Y);
}

//图文信息提示框
- (void)configSubViewsLayoutTextAndImageContent {
    
    CGFloat margin = DEF_MESSAGE_IMAGETEXT_SPACE;
    CGSize textSize = [self.textLb.attributedText boundingRectWithSize:CGSizeMake(MAXFLOAT, 20) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
    CGFloat space = 18.0f;
    
    CGFloat hudWidth = (textSize.width + DEF_TEXT_SPACE * 2) <  DEF_MESSAGE_IMAGETEXT_SIZE.width ?  DEF_MESSAGE_IMAGETEXT_SIZE.width : (textSize.width + DEF_TEXT_SPACE * 2);
    
    CGFloat width = hudWidth - margin * 2;
    CGFloat height = DEF_MESSAGE_IMAGETEXT_SIZE.height - margin * 2 - textSize.height - space;
    self.imageView.frame =  CGRectMake(margin, margin, width, height);
    self.textLb.frame = CGRectMake(DEF_TEXT_SPACE, height + margin + space, hudWidth - DEF_TEXT_SPACE * 2, textSize.height);
    
    CGFloat center_X = DEF_SCREEN_WIDTH/2.0;
    CGFloat center_Y = DEF_SCREEN_HEIGHT/2.0;
    
#ifdef NSFoundationVersionNumber10_10_Max
    if (@available(iOS 11.0, *)) {
        UIEdgeInsets safeInsets = [UIApplication sharedApplication].keyWindow.safeAreaInsets;
        center_Y = (DEF_SCREEN_HEIGHT - safeInsets.bottom - safeInsets.top)/2.0;
    }
#endif
    self.bounds = CGRectMake(0, 0, hudWidth, DEF_MESSAGE_IMAGETEXT_SIZE.height);
    self.center = CGPointMake(center_X, center_Y);
}



#pragma mark - Lazy Load
- (UILabel *)textLb {
    if (!_textLb) {
        _textLb = [[UILabel alloc]init];
        _textLb.numberOfLines = 0;
        _textLb.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_textLb];
    }
    return _textLb;
}


- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc]init];
        _imageView.contentMode = UIViewContentModeScaleAspectFit;
        [self addSubview:_imageView];
    }
    return _imageView;
}

#pragma mark - 获取当前最上层window
- (UIWindow *)lastWindow {
    NSArray *windows = [UIApplication sharedApplication].windows;
    for(UIWindow *window in [windows reverseObjectEnumerator]) {
        if ([window isKindOfClass:[UIWindow class]] &&  CGRectEqualToRect(window.bounds, [UIScreen mainScreen].bounds) && window.hidden == NO)
            return window;
    }
    return [UIApplication sharedApplication].keyWindow;
}

@end
